package com.huawei.crm.sample.application.order;

import com.huawei.crm.sample.application.order.dto.OrderDTO;
import com.huawei.crm.sample.application.order.converter.OrderDTOConverter;
import com.huawei.crm.sample.application.order.validator.OrderValidator;
import com.huawei.crm.sample.application.product.ProductUseCase;
import com.huawei.crm.sample.domain.order.model.aggragate.Order;
import com.huawei.crm.sample.domain.order.model.entity.OrderItem;
import com.huawei.crm.sample.domain.order.repository.OrderRepository;
import com.huawei.crm.sample.domain.order.service.OrderDomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service("orderUseCase")
public class OrderUseCaseImpl implements OrderUseCase {
    private final OrderDomainService orderDomainService;
    private final OrderRepository orderRepository;
    private final ProductUseCase productUseCase;
    private final OrderDTOConverter orderDTOConverter;

    @Autowired
    public OrderUseCaseImpl(OrderDomainService orderDomainService, OrderRepository orderRepository, ProductUseCase productUseCase, OrderDTOConverter orderDTOConverter) {
        this.orderDomainService = orderDomainService;
        this.orderRepository = orderRepository;
        this.productUseCase = productUseCase;
        this.orderDTOConverter = orderDTOConverter;
    }

    @Override
    public OrderDTO placeOrder(OrderDTO orderDTO) {
        OrderValidator.validateForPlaceOrder(orderDTO);
        // 校验商品并扣减库存
        orderDTO.getItems().forEach(item -> {
            productUseCase.decreaseStock(item.getProductId(), item.getQuantity());
        });
        List<OrderItem> items = orderDTO.getItems().stream()
            .map(i -> new OrderItem(i.getProductId(), i.getQuantity(), i.getPrice()))
            .collect(Collectors.toList());
        Order order = orderDomainService.placeOrder(orderDTO.getCustomerId(), items);
        return orderDTOConverter.toDTO(order);
    }

    @Override
    public OrderDTO getOrder(String orderId) {
        Order order = orderRepository.findById(orderId);
        return orderDTOConverter.toDTO(order);
    }
} 